using System;
using System.Collections.Generic;
using System.Text;
using Solo.Core;
using Av.Utils;
using System.Xml;
using System.Threading;

namespace SiteStatusTracker
{
    class Settings
    {

        #region " Name / Version "
        public static string Name = "iSite Tracker";
        public static string Version = "0.9.6";
        public static string NameVersion
        {
            get { return string.Format("{0} (v{1})", Name, Version); }
        }
        #endregion


        /// <summary>
        /// Events which need attention in whole program, i.e. Exit
        /// </summary>
        public class Events
        {
            /// <summary>
            /// How many events are in list
            /// </summary>
            public const int Count = 1;

            /// <summary>
            /// Named ID of events, to help manage them
            /// </summary>
            public class EventId
            {
                public const int Exit = 0;
            }
            //public enum EventId { Exit = 0 };

            /// <summary>
            /// Array of events which could be raised
            /// </summary>
            public static ManualResetEvent[] ArEvents = null;

            static Events()
            {
                ArEvents = new ManualResetEvent[Events.Count];
                ArEvents[EventId.Exit] = new ManualResetEvent(false);
            }

            /// <summary>
            /// Converts ID of event to string name
            /// </summary>
            public static string IdToName(int id)
            {
                switch(id)
                {
                    case EventId.Exit:
                        return "Exit";
                }

                return id.ToString();
            }
        }

        /// <summary>
        /// Gets tracker tasks
        /// </summary>
        public static TrackerItem[] TrackerItems
        {
            get { return m_arTasks; }
        }

        /// <summary>
        /// Task to track
        /// </summary>
        private static TrackerItem[] m_arTasks = null;

        public static void Load()
        {
            string file = Misc.GetPath() + "config.xml";
            Log4cs.Log("Loading configuration from: {0}", file);
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(file);
            m_arTasks = new TrackerItem[xmlDoc.DocumentElement.ChildNodes.Count];
            Log4cs.Log(Importance.Debug, "There are {0} items in configuration file", xmlDoc.DocumentElement.ChildNodes.Count);

            // How many correct configured tasks
            int totalR = 0;

            // List all tasks
            for(int i = 0; i < xmlDoc.DocumentElement.ChildNodes.Count; i++)
            {
                //Log4cs.Log(Importance.Debug, "XML: {0}", xmlDoc.DocumentElement.ChildNodes[i].Name);

                XmlNode taskNode = xmlDoc.DocumentElement.ChildNodes[i];
                //Log4cs.Log(Importance.Debug, "Task node name: {0}", taskNode.Name);
            
                // If this is taks configuration and has some values
                if((taskNode.Name.ToLower() == "task") && taskNode.HasChildNodes)
                {

                    m_arTasks[totalR] = new TrackerItem();

                    // List all task configuration fields
                    foreach(XmlNode node in taskNode.ChildNodes)
                    {
                        if(node.HasChildNodes)
                        {
                            switch(node.Name.ToLower())
                            {
                                case "name":
                                    m_arTasks[totalR].Name = node.FirstChild.Value.Trim();
                                    Log4cs.Log(Importance.Debug, "Task name: {0}", m_arTasks[i].Name);
                                    break;
                                case "uri":
                                    m_arTasks[totalR].SiteUri = new Uri(node.FirstChild.Value.Trim());
                                    break;
                                case "frequencys":
                                    m_arTasks[totalR].FrequencyS = Int32.Parse(node.FirstChild.Value.Trim());
                                    break;
                                case "texttosearch":
                                    m_arTasks[totalR].TextInPage = node.FirstChild.Value.Trim();
                                    break;
                                case "popuponoks":
                                    m_arTasks[totalR].PopupOkS = Int32.Parse(node.FirstChild.Value.Trim());
                                    break;
                                case "popuponfails":
                                    m_arTasks[totalR].PopupFailS = Int32.Parse(node.FirstChild.Value.Trim());
                                    break;

                                default:
                                    Log4cs.Log(Importance.Warning, "task configuration does not support tag <{0}>!", node.Name);
                                    break;
                            }
                        }
                    }

                    // Got correct task configuration
                    totalR++;

                }else
                {
                    Log4cs.Log(Importance.Warning, "Unknown tag in configuration: {0}!", taskNode.Name);
                }  // END ELSE IF (if this is task configuration)
            }

            // If configured task count is less than items in config file
            if( (totalR != 0) && (totalR < m_arTasks.Length) )
            {
                Log4cs.Log(Importance.Debug, "Resizing task configuration array from {0} to {1}...", m_arTasks.Length, totalR);
                Array.Resize(ref m_arTasks, totalR);
            }

            if(m_arTasks.Length > 1)
            {
                Log4cs.Log(Importance.Warning, "Sharavary-version supports only 1 task :)");
            }
        }

        public static string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("Settings for {0} (v{1})", Name, Version);
            sb.AppendLine();

            for(int i = 0; (m_arTasks != null) && (i < m_arTasks.Length); i++)
            {
                sb.AppendLine(m_arTasks[i].ToString());
                sb.AppendLine("--------------");
            }

            return sb.ToString();
        }

    }
}
